using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Ltf.Remoting.Settings;
using System.Runtime.InteropServices;

namespace Ltf.Remoting.TFAccess
{
	public class FSDifRepository : IDifRepository
	{
		[DllImport("imagehlp.dll")]
		public static extern int MapFileAndCheckSumA(string fileName, ref int headerSum, ref int checkSum);

		#region IDifRepository Members

		public void PrepCache(string fsPath)
		{ 
			// no server stuff to cache
		}

		public bool FolderExists(string path)
		{
			return Directory.Exists(path);
		}

		public bool FileExists(string path)
		{
			return File.Exists(path);
		}

		public bool FileOrFolderExists(string path)
		{
			return (Directory.Exists(path) || File.Exists(path));
		}

		public IEnumerable<string> GetFolderItems(string path, DifItemType itemType)
		{
			if (FolderExists(path))
			{
				if (itemType == DifItemType.Any || itemType == DifItemType.File)
				{
					foreach (string filename in Directory.GetFiles(path))
					{
						yield return filename;
					}
				}
				if (itemType == DifItemType.Any || itemType == DifItemType.Folder)
				{
					foreach (string filename in Directory.GetDirectories(path))
					{
						yield return filename;
					}
				}
			}
			else
			{
				throw new System.IO.DirectoryNotFoundException(string.Format("Folder {0} does not exist.", path));
			}
		}

		public Stream GetFileItemStream(string path)
		{
			return File.OpenRead(path);
		}

		public int GetFileChecksum(string path)
		{
			int hs1 = 0, cs1 = 0;
			int fh1 = MapFileAndCheckSumA(path, ref hs1, ref cs1);

			return cs1;
		}

		public bool LastItemHasPotentialConflict
		{ get { return false; } }

		public int GetQuickItemCount(TFSettings settings, string path)
		{
			List<string> list = new List<string>();
			string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
			foreach (string f in files)
				if (settings.IsFullFilePathIncluded(f) && !Directory.Exists(f)) list.Add(f);
			return list.Count;

		}

		public string GetVersionQualifiedPath(string path)
		{
			return path;
		}

#endregion
	}
}
